package com.itic.mall.mobile.orders;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.type.AfterSaleDealType;
import com.itic.appbase.framework.type.AfterSaleType;
import com.itic.appbase.framework.type.LivingRateType;
import com.itic.appbase.framework.type.OrderType;
import com.itic.appbase.framework.type.PreType;
import com.itic.appbase.framework.type.RemindState;
import com.itic.appbase.framework.type.TaxCompany;
import com.itic.appbase.framework.utils.DateHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.ValueHelper;
import com.itic.mall.mobile.base.BaseMobileInterface;
import com.itic.mall.mobile.goods.vo.GoodsDetailVo;
import com.itic.mall.mobile.goods.vo.GoodsItemVo;
import com.itic.mall.system.finance.makeMoneyLog.persistence.model.FinanceUserMakeMoneyLog;
import com.itic.mall.system.finance.makeMoneyLog.service.FinanceUserMakeMoneyLogService;
import com.itic.mall.system.goods.coupon.persistence.model.GoodsCoupon;
import com.itic.mall.system.goods.coupon.persistence.model.GoodsCouponExample;
import com.itic.mall.system.goods.coupon.service.GoodsCouponService;
import com.itic.mall.system.goods.goodssku.persistence.model.GoodsSku;
import com.itic.mall.system.goods.goodssku.service.GoodsSkuService;
import com.itic.mall.system.goods.goodsspu.persistence.model.GoodsSpu;
import com.itic.mall.system.goods.goodsspu.service.GoodsSpuService;
import com.itic.mall.system.goods.judge.persistence.model.GoodsJudge;
import com.itic.mall.system.goods.judge.service.GoodsJudgeService;
import com.itic.mall.system.goods.paramgoods.service.ParamGoodsService;
import com.itic.mall.system.goods.skucoupon.service.SkuCouponService;
import com.itic.mall.system.orders.aftersale.persistence.model.OrdersAftersale;
import com.itic.mall.system.orders.aftersale.persistence.model.OrdersAftersaleExample;
import com.itic.mall.system.orders.aftersale.service.OrdersAftersaleService;
import com.itic.mall.system.orders.detail.persistence.model.OrdersDetail;
import com.itic.mall.system.orders.detail.persistence.model.OrdersDetailExample;
import com.itic.mall.system.orders.detail.persistence.model.OrdersDetailExample.Criteria;
import com.itic.mall.system.orders.detail.service.OrdersDetailService;
import com.itic.mall.system.orders.express.persistence.model.OrderExpress;
import com.itic.mall.system.orders.express.persistence.model.OrderExpressExample;
import com.itic.mall.system.orders.express.service.OrderExpressService;
import com.itic.mall.system.orders.item.persistence.model.OrdersItem;
import com.itic.mall.system.orders.item.persistence.model.OrdersItemExample;
import com.itic.mall.system.orders.item.service.OrdersItemService;
import com.itic.mall.system.orders.remindsend.persistence.model.OrdersRemindSend;
import com.itic.mall.system.orders.remindsend.persistence.model.OrdersRemindSendExample;
import com.itic.mall.system.orders.remindsend.service.OrdersRemindSendService;
import com.itic.mall.system.pay.userlog.persistence.model.PayUserlog;
import com.itic.mall.system.pay.userlog.service.PayUserlogService;
import com.itic.mall.system.project.proexpress.persistence.model.ProjectExpress;
import com.itic.mall.system.project.score.service.ProjectScoreService;
import com.itic.mall.system.users.address.persistence.model.Usersaddress;
import com.itic.mall.system.users.address.persistence.model.UsersaddressExample;
import com.itic.mall.system.users.address.service.UsersaddressService;
import com.itic.mall.system.users.pointslog.service.UsersPointslogService;
import com.itic.mall.system.users.usercoupon.persistence.model.UsersCoupon;
import com.itic.mall.system.users.usercoupon.persistence.model.UsersCouponExample;
import com.itic.mall.system.users.usercoupon.service.UsersCouponService;
import com.itic.mall.system.users.usersmall.persistence.model.UsersMall;




/**
 * 订单接口
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value = "/mobile/orders")
public class OrdersdetailInterface extends BaseMobileInterface {

	@Autowired
	private OrdersRemindSendService ordersRemindSendService;
	@Autowired
	private ParamGoodsService paramGoodsService;
	@Autowired
	private OrdersDetailService ordersDetailService;
	@Autowired
	private OrderExpressService orderExpressService;
	@Autowired
	private OrdersAftersaleService ordersAftersaleService;
	@Autowired
	private UsersCouponService usersCouponService;
	@Autowired
	private GoodsCouponService goodsCouponService;
	@Autowired
	private UsersaddressService usersaddressService;
	@Autowired
	private OrdersItemService ordersItemService;
	@Autowired
	private UsersPointslogService usersPointslogService;
	@Autowired
	private PayUserlogService payUserlogService;
	@Autowired
	private GoodsJudgeService goodsJudgeService;
	@Autowired 
	private GoodsSpuService goodsSpuService;
	@Autowired
	private GoodsSkuService goodsSkuService;
	@Autowired
	private SkuCouponService skuCouponService;
	@Autowired
	private FinanceUserMakeMoneyLogService financeUserMakeMoneyLogService;
	@Autowired
	private ProjectScoreService projectScoreService;
	private static String[] ignoreProperties = new String[] { "createUser", "isEffective", "updateTime", "orgCode" };
	
	
	/**
	 * 取消订单
	 * @param request
	 * @param response
	 * @param token
	 * @param appId
	 * @return
	 */
	@RequestMapping(value = "/cancelorders")
	@ResponseBody
	public Map<String, Object> cancelorders(HttpServletRequest request, HttpServletResponse response,String token,String appId, String orderNo) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try{
			String result = FAIL;
			if(StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId) && StringHelper.isNotBlank(orderNo)){
				UsersMall usersMall = getUsersByTokenAndAppId(token, appId);
				if(usersMall != null){
					String userId = usersMall.getId();
					OrdersDetail ordersDetail = getOrderByOrderNo(userId,orderNo, "1");//订单状态（1:待付款，2：已付款，3：待发货，4：待收货，5：已收货，待评价）
					if(ordersDetail != null){
						ordersDetail.setIsEffective(DBConst.FALSE);
						//ordersDetail.setState(OrderType.close.getState());
						result = ordersDetailService.edit(ordersDetail);
						if(SUCCESS.equals(result)){
							List<OrdersItem> itemList = getorderItem(orderNo);
							if(itemList.size()>0){
								for(OrdersItem ordersItem: itemList){
									ordersItem.setIsEffective(DBConst.FALSE);
									//ordersItem.setState(OrderType.close.getState());
									result = ordersItemService.edit(ordersItem);
									if(FAIL.equals(result)){
										break;
									}
									errorCode = SUCCESS_ERROR_CODE;
									errorMsg = SUCCESS_ERROR_MSG;
								}
							}	
						}
					}else{
						errorCode = ORDER_NULL_ERROR_CODE;
						errorMsg = ORDER_NULL_ERROR_MSG;
					}
				}else{
					errorCode = LOGIN_ERROR_CODE;
					errorMsg = LOGIN_ERROR_MSG;
				}
				
			}
		}catch(Exception e){
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "cancelorders", e.toString(), "取消订单", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		return resultMap;
		}
	
	/**
	 * 删除订单
	 * @param request
	 * @param response
	 * @param token
	 * @param appId
	 * @return
	 */
	@RequestMapping(value = "/delorders")
	@ResponseBody
	public Map<String, Object> delorders(HttpServletRequest request, HttpServletResponse response, String token,String appId,String orderNo) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try{
			String result = FAIL;
			if(StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId) && StringHelper.isNotBlank(orderNo)){
				UsersMall usersMall = getUsersByTokenAndAppId(token, appId);
				if(usersMall != null){
					String userId = usersMall.getId();
					OrdersDetail ordersDetail = getOrderByOrderNo(userId,orderNo,OrderType.finished.getState());//订单状态（1:待付款，2：已付款，3：待发货，4：待收货，5：已收货，待评价）
					if(ordersDetail != null){
						ordersDetail.setIsEffective(DBConst.FALSE);
						ordersDetail.setIsDelete(DBConst.FALSE);
						result = ordersDetailService.edit(ordersDetail);
					/*	if(SUCCESS.equals(result)){
							List<OrdersItem> itemList = getorderItem(orderNo);
							if(itemList.size()>0){
								for(OrdersItem ordersItem: itemList){
									ordersItem.setIsEffective(DBConst.FALSE);
									result = ordersItemService.edit(ordersItem);
									if(FAIL.equals(result)){
										break;
									}
									errorCode = SUCCESS_ERROR_CODE;
									errorMsg = SUCCESS_ERROR_MSG;
								}
							}	
						}*/
						errorCode = SUCCESS_ERROR_CODE;
						errorMsg = SUCCESS_ERROR_MSG;
					}else{
						errorCode = ORDER_NULL_ERROR_CODE;
						errorMsg = ORDER_NULL_ERROR_MSG;
					}
				}else{
					errorCode = LOGIN_ERROR_CODE;
					errorMsg = LOGIN_ERROR_MSG;
				}
			}
		}catch(Exception e){
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "delorders", e.toString(), "删除订单", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		return resultMap;
		}
	/**
	 * 我的订单
	 * 
	 * @param request
	 * @param response
	 * @param token
	 * @param appId
	 * @return
	 */
	@RequestMapping(value = "/myorders")
	@ResponseBody
	public Map<String, Object> myorders(HttpServletRequest request, HttpServletResponse response, String token,
			String appId) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
    		UsersMall usersMall = getUsersByTokenAndAppId(token,appId);
    		if(usersMall != null){
     			String userid = usersMall.getId();
    			List<Map<String, Object>> orderlist = new ArrayList<Map<String, Object>>();			
    			OrdersDetailExample example = new OrdersDetailExample();
    			Criteria criteria = example.createCriteria();
    			criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    			criteria.andUserIdEqualTo(userid);
    			criteria.andIsDeleteEqualTo(DBConst.TRUE);
    			example.setOrderByClause(" CREATE_TIME desc");
    			// 订单状态（1:待付款，2：已付款，3：待发货，4：待收货，5：已收货，待评价）
    			List<OrdersDetail> list = ordersDetailService.list(example);
				for(OrdersDetail ordersDetail:list){
					double expressFee = 0;
					double totalprice = 0;
					int count = 0;
					Map<String, Object> dataMap = new HashMap<String, Object>();
					String orderNo = ordersDetail.getOrderNo();
					String state = ordersDetail.getState();
					//计算总计运费
					String fee = String.valueOf(ordersDetail.getExpressFee());
					if(fee !="null"){
    					expressFee = ordersDetail.getExpressFee();
					}
					// 商品信息
					OrdersItemExample exampleg = new OrdersItemExample();
					com.itic.mall.system.orders.item.persistence.model.OrdersItemExample.Criteria criteriag = exampleg
							.createCriteria();
					criteriag.andIsEffectiveEqualTo(DBConst.TRUE);
					criteriag.andOrderNoEqualTo(orderNo);
					List<OrdersItem> listg = ordersItemService.list(exampleg);
					if(listg.size()>0){
						//总计商品件数
						count = listg.size();
						List<GoodsItemVo> listvo = new ArrayList<GoodsItemVo>();
						for(OrdersItem ordersItem: listg){
							GoodsItemVo goodsItemVo = new GoodsItemVo();
							goodsItemVo.setSkuId(ordersItem.getSkuId());
							goodsItemVo.setState(state);
							goodsItemVo.setOrderNo(orderNo);
							goodsItemVo.setGoodsId(ordersItem.getGoodsId());
							goodsItemVo.setGoodsImg(ordersItem.getGoodsImg());
							goodsItemVo.setGoodsName(ordersItem.getGoodsName());
							goodsItemVo.setPrice(ordersItem.getPrice() == null?0:ordersItem.getPrice());
							goodsItemVo.setOrginPrice(ordersItem.getOrginPrice() == null? 0:ordersItem.getOrginPrice());
							goodsItemVo.setCount(ordersItem.getCount()==null?0:ordersItem.getCount());
							goodsItemVo.setStoreId(ordersItem.getStoreId());
							Map<String, Object> paramMap =this.goodsSkuService.getGoodSkuById(ordersItem.getSkuId());// 商品规格信息
							
							//fee = String.valueOf(goodsItemVo.getPrice());
							totalprice =ordersDetail.getActualPay();
							goodsItemVo.setParam(paramMap);
							listvo.add(goodsItemVo);
						}
						dataMap.put(DATA, listvo);//一个订单下的所有订单项
					}
					dataMap.put("orderNo", orderNo);
					dataMap.put("totalcount", count);//总计商品件数
					dataMap.put("totalprice", totalprice);//总合计钱数
					dataMap.put("expressFee", expressFee);//总合计运费
					dataMap.put("state", state);
					orderlist.add(dataMap);
				}
    			resultMap.put("orderList", orderlist);
    			errorCode = SUCCESS_ERROR_CODE;
				errorMsg = SUCCESS_ERROR_MSG;
    		}else{
    			errorCode = LOGIN_ERROR_CODE;
				errorMsg = LOGIN_ERROR_MSG;
    		}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "myorders", e.toString(), "我的订单", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}
	/**
	 * 根据用户ID和状态信息获取相应状态的订单信息
	 * @param request
	 * @param response
	 * @param userid
	 * @param state
	 * @return
	 */
	public Map<String, Object> getordersByState(HttpServletRequest request, HttpServletResponse response, String userid,String state) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try{
			List<Map<String, Object>> orderlist = new ArrayList<Map<String, Object>>();			
			OrdersDetailExample example = new OrdersDetailExample();
			Criteria criteria = example.createCriteria();
			criteria.andIsEffectiveEqualTo(DBConst.TRUE);
			//添加前台是否删除
			criteria.andIsDeleteEqualTo(DBConst.TRUE);
			criteria.andUserIdEqualTo(userid);
			criteria.andIsDeleteEqualTo(DBConst.TRUE);
			// 订单状态（1:待付款，2：已付款，3：待发货，4：待收货，5：已收货，待评价）
			criteria.andStateEqualTo(state);// 未付款
			example.setOrderByClause(" CREATE_TIME desc");
			List<OrdersDetail> list = ordersDetailService.list(example);
			if (list.size() > 0) {
				for(OrdersDetail ordersDetail:list){
					double expressFee = 0;
					double totalprice = 0;
					int count = 0;
					Map<String, Object> dataMap = new HashMap<String, Object>();
					String orderNo = ordersDetail.getOrderNo();
					//计算总计运费
					Double fee = ordersDetail.getExpressFee();
					if(fee != null){
    					expressFee = ordersDetail.getExpressFee();
					}
					// 商品信息
					OrdersItemExample exampleg = new OrdersItemExample();
					com.itic.mall.system.orders.item.persistence.model.OrdersItemExample.Criteria criteriag = exampleg
							.createCriteria();
					criteriag.andIsEffectiveEqualTo(DBConst.TRUE);
					criteriag.andOrderNoEqualTo(orderNo);
					List<OrdersItem> listg = ordersItemService.list(exampleg);
					if(listg.size()>0){
						//总计商品件数
						
						List<GoodsItemVo> listvo = new ArrayList<GoodsItemVo>();
						for(OrdersItem ordersItem: listg){
							count+=ordersItem.getCount();
							GoodsItemVo goodsItemVo = new GoodsItemVo();
							goodsItemVo.setSkuId(ordersItem.getSkuId());
							goodsItemVo.setState(state);
							goodsItemVo.setOrderNo(orderNo);
							goodsItemVo.setGoodsId(ordersItem.getGoodsId());
							goodsItemVo.setGoodsImg(ordersItem.getGoodsImg());
							goodsItemVo.setGoodsName(ordersItem.getGoodsName());
							GoodsDetailVo goodsDetailVo = this.goodsSkuService.getSkuDetailBySkuId(ordersItem.getSkuId(), 1);
							double couponPrice = goodsDetailVo.getPrice();
							goodsItemVo.setPrice(couponPrice);
							goodsItemVo.setOrginPrice(ordersItem.getPrice()==null?0:ordersItem.getPrice());
							goodsItemVo.setCount(ordersItem.getCount()==null?0:ordersItem.getCount());
							goodsItemVo.setStoreId(ordersItem.getStoreId());
							Map<String, Object> paramMap = this.goodsSkuService.getGoodSkuById(ordersItem.getSkuId());
							goodsItemVo.setParam(paramMap);
							listvo.add(goodsItemVo);
							totalprice = totalprice + ordersItem.getActualPay();
						}
						dataMap.put(DATA, listvo);//一个订单下的所有订单项
					}
					dataMap.put("orderNo", orderNo);
					dataMap.put("totalcount", count);//总计商品件数
					dataMap.put("totalprice", ordersDetail.getActualPay());//总合计钱数
					dataMap.put("expressFee", expressFee);//总合计运费
					orderlist.add(dataMap);
				}
				resultMap.put("orderList", orderlist);
			}
		}catch(Exception e){
			logException("OrdersdetailInterface", "根据用户ID和状态信息获取相应状态的订单信息失败", e.toString(), "根据用户ID和状态信息获取相应状态的订单信息", e);
		}
		return resultMap;
		}
	/**
	 * 根据订单状态获取订单
	 * @param request
	 * @param response
	 * @param token
	 * @param appId
	 * @param state
	 * @return
	 */
	@RequestMapping(value = "/getOrdersByState")
	@ResponseBody
	public Map<String, Object> getOrdersByState(HttpServletRequest request, HttpServletResponse response, String token,
			String appId,String state) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try{
			if (StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId) && StringHelper.isNotBlank(state)) {
				UsersMall usersMall = getUsersByTokenAndAppId(token, appId);
				if (usersMall != null) {
					String userid = usersMall.getId();
					//订单状态（1:待付款，2：已付款，3：待发货，4：待收货，5：已收货，待评价）
					resultMap = getordersByState(request, response, userid,state);
					errorCode = SUCCESS_ERROR_CODE;
					errorMsg = SUCCESS_ERROR_MSG;
					} else {
					errorCode = LOGIN_ERROR_CODE;
					errorMsg = LOGIN_ERROR_MSG;
				}
			}		
		}catch(Exception e){
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "notpayed", e.toString(), "待支付订单", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
		}
	/**
	 * 待支付订单
	 * 
	 * @param request
	 * @param response
	 * @param token
	 * @param appId
	 * @return
	 */
	@RequestMapping(value = "/notpayed")
	@ResponseBody
	public Map<String, Object> notpayed(HttpServletRequest request, HttpServletResponse response, String token,
			String appId) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			if (StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId)) {
				UsersMall usersMall = getUsersByTokenAndAppId(token, appId);
				if (usersMall != null) {
					String userid = usersMall.getId();
					//订单状态（1:待付款，2：已付款，3：待发货，4：待收货，5：已收货，待评价）
					resultMap = getordersByState(request, response, userid,"1");
					errorCode = SUCCESS_ERROR_CODE;
					errorMsg = SUCCESS_ERROR_MSG;
					} else {
					errorCode = LOGIN_ERROR_CODE;
					errorMsg = LOGIN_ERROR_MSG;
				}
			}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "notpayed", e.toString(), "待支付订单", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}
	
	/**
	 * 待支付订单详情
	 * 
	 * @param request
	 * @param response
	 * @param token
	 * @param appId
	 * @return
	 */
	@RequestMapping(value = "/notpayeddetail")
	@ResponseBody
	public Map<String, Object> notpayeddetail(HttpServletRequest request, HttpServletResponse response,
			String token,String appId,String orderNo) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			UsersMall usersMall = getUsersByTokenAndAppId(token, appId);
			if(usersMall != null){
				if(StringHelper.isNotBlank(orderNo)){
					String userId = usersMall.getId();
					/*OrdersDetailExample example = new OrdersDetailExample();
					Criteria criteria = example.createCriteria();
					criteria.andIsEffectiveEqualTo(DBConst.TRUE);
					criteria.andOrderNoEqualTo(orderNo);
					// 订单状态（1:待付款，2：已付款，3：待发货，4：待收货，5：已收货，待评价）
					criteria.andStateEqualTo("1");
					criteria.andUserIdEqualTo(userId);
					criteria.andIsDeleteEqualTo(DBConst.TRUE);
					List<OrdersDetail> list = ordersDetailService.list(example);*/
					OrderVo Vo = getOrdersDetailByOrderNo(request, response, orderNo, "1");
					if(Vo != null){
						resultMap.put(DATA, Vo);
						errorCode = SUCCESS_ERROR_CODE;
						errorMsg = SUCCESS_ERROR_MSG;
					}else{
						errorCode = ORDER_ERROR_CODE;
						errorMsg = ORDER_ERROR_MSG;
					}
				}
			}else {
				errorCode = LOGIN_ERROR_CODE;
				errorMsg = LOGIN_ERROR_MSG;
			}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "notpayeddetail", e.toString(), "代支付订单详情", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}
	/**
	 * 订单添加新地址
	 * @param request
	 * @param response
	 * @param orderNo
	 * @param userId
	 * @param addressId
	 * @return
	 */
	@RequestMapping(value = "/addreceiverAddr")
	@ResponseBody
	public Map<String, Object> addreceiverAddr(HttpServletRequest request, HttpServletResponse response, String orderNo,String userId,String addressId) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try{
			if(StringHelper.isNotBlank(orderNo) && StringHelper.isNotBlank(userId) && StringHelper.isNotBlank(addressId)){
				OrdersDetailExample example = new OrdersDetailExample();
				Criteria criteria = example.createCriteria();
				criteria.andIsEffectiveEqualTo(DBConst.TRUE);
				criteria.andOrderNoEqualTo(orderNo);
				// 订单状态（1:待付款，2：已付款，3：待发货，4：待收货，5：已收货，待评价）
				criteria.andStateEqualTo("1");// 未付款
				List<OrdersDetail> list = ordersDetailService.list(example);
				if(list.size()>0){
					UsersaddressExample examplere = new UsersaddressExample();
					com.itic.mall.system.users.address.persistence.model.UsersaddressExample.Criteria criteriare = examplere
							.createCriteria();
					criteriare.andIdEqualTo(addressId);
					criteriare.andUserIdEqualTo(userId);
					criteriare.andIsEffectiveEqualTo(DBConst.TRUE);
					List<Usersaddress> listre = usersaddressService.list(examplere);
					if(listre.size()>0){
						list.get(0).setAddressId(addressId);
						String result  = ordersDetailService.edit(list.get(0));
						if(SUCCESS.equals(result)){
							errorCode = SUCCESS_ERROR_CODE;
							errorMsg = SUCCESS_ERROR_MSG;
						}
					}else{
						errorCode = RECEIVER_ERROR_CODE;
						errorMsg = RECEIVER_ERROR_MSG;
					}
				}else{
					errorCode = ORDER_ERROR_CODE;
					errorMsg = ORDER_ERROR_MSG;
				}
 			}
		}catch(Exception e){
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "addreceiverAddr", e.toString(), "订单添加新地址", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
		}
	
	/**
	 * 代发货订单
	 * 
	 * @param request
	 * @param response
	 * @param token
	 * @param appId
	 * @return
	 */
	@RequestMapping(value = "/notsended")
	@ResponseBody
	public Map<String, Object> notsended(HttpServletRequest request, HttpServletResponse response, String token,
			String appId) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			if (StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId)) {
				UsersMall usersMall = getUsersByTokenAndAppId(token, appId);
				if (usersMall != null) {
					String userid = usersMall.getId();
					resultMap = getordersByState(request, response, userid,"3");
					errorCode = SUCCESS_ERROR_CODE;
					errorMsg = SUCCESS_ERROR_MSG;
					} else {
					errorCode = LOGIN_ERROR_CODE;
					errorMsg = LOGIN_ERROR_MSG;
				}
			}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "notsended", e.toString(), "代发货订单", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}

	/**
	 * 待发货订单详情
	 * 
	 * @param request
	 * @param response
	 * @param token
	 * @param appId
	 * @return
	 */
	@RequestMapping(value = "/notsendeddetail")
	@ResponseBody
	public Map<String, Object> notsendeddetail(HttpServletRequest request, HttpServletResponse response,
			String orderNo,String token,String appId) {

 		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			if(StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId)){
				UsersMall usersMall = getUsersByTokenAndAppId(token, appId);
				if(usersMall != null){
					if(StringHelper.isNotBlank(orderNo)){
						String userId = usersMall.getId();
						OrdersDetailExample example = new OrdersDetailExample();
						Criteria criteria = example.createCriteria();
						criteria.andIsEffectiveEqualTo(DBConst.TRUE);
						criteria.andOrderNoEqualTo(orderNo);
						// 订单状态（1:待付款，2：已付款，3：待发货，4：待收货，5：已收货，待评价）
						criteria.andStateEqualTo("3");
						criteria.andUserIdEqualTo(userId);
						List<OrdersDetail> list = ordersDetailService.list(example);
						if(list.size()>0){
							OrderVo Vo = getOrdersDetailByOrderNo(request, response, orderNo, "3");
							if(Vo != null){
								resultMap.put(DATA, Vo);
								errorCode = SUCCESS_ERROR_CODE;
								errorMsg = SUCCESS_ERROR_MSG;
							}else{
								errorCode = ORDER_ERROR_CODE;
								errorMsg = ORDER_ERROR_MSG;
							}
						}else{
							errorCode = ORDER_ERROR_CODE;
							errorMsg = ORDER_ERROR_MSG;
						}	
					}
				}else {
					errorCode = LOGIN_ERROR_CODE;
					errorMsg = LOGIN_ERROR_MSG;
				}
			}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "notsendeddetail", e.toString(), "代发货订单详情", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;

	}

	/**
	 * 待收货订单
	 * 
	 * @param request
	 * @param response
	 * @param token
	 * @param appId
	 * @return
	 */
	@RequestMapping(value = "/notrecieved")
	@ResponseBody
	public Map<String, Object> notrecieved(HttpServletRequest request, HttpServletResponse response, String token,
			String appId) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			if (StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId)) {
				UsersMall usersMall = getUsersByTokenAndAppId(token, appId);
				if (usersMall != null) {
					String userid = usersMall.getId();
					resultMap = getordersByState(request, response, userid,"4");
					errorCode = SUCCESS_ERROR_CODE;
					errorMsg = SUCCESS_ERROR_MSG;
					} else {
					errorCode = LOGIN_ERROR_CODE;
					errorMsg = LOGIN_ERROR_MSG;
				}
			}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "notrecieved", e.toString(), "待收货订单", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}
	/**
	 * 确认收货
	 * @param request
	 * @param response
	 * @param orderNo
	 * @param goodsId
	 * @param token
	 * @param appId
	 * @return
	 */
	@RequestMapping(value = "/confirmReceive")
	@ResponseBody
	public Map<String, Object> confirmReceive(HttpServletRequest request, HttpServletResponse response,
			String orderNo,String token,String appId) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try{
			String result = FAIL;
			UsersMall usersMall = getUsersByTokenAndAppId(token, appId);
			if(usersMall != null){
				if(StringHelper.isNotBlank(orderNo)){
					OrdersDetail ordersDetail = this.getOrderdetail(orderNo);
					if(ordersDetail!=null) {
						List<OrdersItem> ordersItems = this.ordersItemService.getOrderItemsByOrderNo(orderNo);
						boolean flag = true;
						for(OrdersItem item : ordersItems) {
							String state = item.getState();
							if(OrderType.Sending.getState().equals(state)) {
								flag = false;
								break;
							}
						}
						if(flag) {
							boolean orderState = true;
							for(OrdersItem item : ordersItems) {
								if(OrderType.Sended.getState().equals(item.getState())) {
									item.setState(OrderType.Judgeing.getState());
									item.setConfirmTime(new Date());
									this.ordersItemService.edit(item);
								}else
									orderState = false;
							}
							if(orderState){
								 ordersDetail.setState(OrderType.Judgeing.getState());
								 ordersDetail.setLivingType("1");
								 this.ordersDetailService.edit(ordersDetail);
								 // 添加用户生钱金额 以及消费额
								 this.usersMallService.addUserLivingMOney(ordersDetail, TaxCompany.yh);
							}
							errorCode = SUCCESS_ERROR_CODE;
							errorMsg = SUCCESS_ERROR_MSG;
						}else {
							errorCode = ORDER_HAD_SENDING_CODE;
							errorMsg = ORDER_HAD_SENDING_MSG;
						}
					}else {
						errorCode = ORDER_NULL_ERROR_CODE;
						errorMsg = ORDER_NULL_ERROR_MSG;
					}
				}
			}else {
				errorCode = LOGIN_ERROR_CODE;
				errorMsg = LOGIN_ERROR_MSG;
			}
		}catch(Exception e){
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "confirmReceive", e.toString(), "确认收货", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
		}
	/**
	 * 待发货订单详情
	 * 
	 * @param request
	 * @param response
	 * @param token
	 * @param appId
	 * @return
	 */
	@RequestMapping(value = "/notrecieveddetail")
	@ResponseBody
	public Map<String, Object> notrecieveddetail(HttpServletRequest request, HttpServletResponse response,
			String orderNo,String token,String appId) {
 		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			if(StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId)){
				UsersMall usersMall = getUsersByTokenAndAppId(token, appId);
				if(usersMall != null){
					if(StringHelper.isNotBlank(orderNo)){
						String userId = usersMall.getId();
						OrdersDetailExample example = new OrdersDetailExample();
						Criteria criteria = example.createCriteria();
						criteria.andIsEffectiveEqualTo(DBConst.TRUE);
						criteria.andOrderNoEqualTo(orderNo);
						// 订单状态（1:待付款，2：已付款，3：待发货，4：待收货，5：已收货，待评价）
						criteria.andStateEqualTo("4");
						criteria.andUserIdEqualTo(userId);
						List<OrdersDetail> list = ordersDetailService.list(example);
						if(list.size()>0){
							OrderVo Vo = getOrdersDetailByOrderNo(request, response, orderNo, "4");
							if(Vo != null){
								resultMap.put(DATA, Vo);
								errorCode = SUCCESS_ERROR_CODE;
								errorMsg = SUCCESS_ERROR_MSG;
							}else{
								errorCode = ORDER_ERROR_CODE;
								errorMsg = ORDER_ERROR_MSG;
							}
						}else{
							errorCode = ORDER_ERROR_CODE;
							errorMsg = ORDER_ERROR_MSG;
						}	
					}
				}else {
					errorCode = LOGIN_ERROR_CODE;
					errorMsg = LOGIN_ERROR_MSG;
				}
			}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "notrecieveddetail", e.toString(), "待发货订单详情", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}

	/**
	 * 待评价订单
	 * 
	 * @param request
	 * @param response
	 * @param token
	 * @param appId
	 * @return
	 */
	@RequestMapping(value = "/notjudged")
	@ResponseBody
	public Map<String, Object> notjudged(HttpServletRequest request, HttpServletResponse response, String token,
			String appId) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			if (StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId)) {
				UsersMall usersMall = getUsersByTokenAndAppId(token, appId);
				if (usersMall != null) {
					String userid = usersMall.getId();
					resultMap = getordersByState(request, response, userid,"5");
					errorCode = SUCCESS_ERROR_CODE;
					errorMsg = SUCCESS_ERROR_MSG;
				} else {
					errorCode = LOGIN_ERROR_CODE;
					errorMsg = LOGIN_ERROR_MSG;
				}
			}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "notjudged", e.toString(), "待评价订单", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}

	/**
	 * 待评价订单详情
	 * 
	 * @param request
	 * @param response
	 * @param token
	 * @param appId
	 * @return
	 */
	@RequestMapping(value = "/notjudgeddetail")
	@ResponseBody
	public Map<String, Object> notjudgeddetail(HttpServletRequest request, HttpServletResponse response,
			String orderNo,String token,String appId) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			if(StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId)){
				UsersMall usersMall = getUsersByTokenAndAppId(token, appId);
				if(usersMall != null){
					if(StringHelper.isNotBlank(orderNo)){
						String userId = usersMall.getId();
						OrdersDetailExample example = new OrdersDetailExample();
						Criteria criteria = example.createCriteria();
						criteria.andIsEffectiveEqualTo(DBConst.TRUE);
						criteria.andOrderNoEqualTo(orderNo);
						// 订单状态（1:待付款，2：已付款，3：待发货，4：待收货，5：已收货，待评价）
						//criteria.andStateEqualTo("5");
						criteria.andUserIdEqualTo(userId);
						List<OrdersDetail> list = ordersDetailService.list(example);
						if(list.size()>0){
							OrderVo Vo = getOrdersDetailByOrderNo(request, response, orderNo, "5");
							if(Vo != null){
								resultMap.put(DATA, Vo);
								errorCode = SUCCESS_ERROR_CODE;
								errorMsg = SUCCESS_ERROR_MSG;
							}else{
								errorCode = ORDER_NULL_ERROR_CODE;
								errorMsg = ORDER_NULL_ERROR_MSG;
							}
						}else{
							errorCode = ORDER_NULL_ERROR_CODE;
							errorMsg = ORDER_NULL_ERROR_MSG;
						}	
					}
				}else {
					errorCode = LOGIN_ERROR_CODE;
					errorMsg = LOGIN_ERROR_MSG;
				}
			}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "notjudgeddetail", e.toString(), "待评价订单详情", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		return resultMap;
	}
	/**
	 * 订单详情
	 * @param request
	 * @param response
	 * @param orderNo
	 * @param token
	 * @param appId
	 * @return
	 */
	@RequestMapping(value = "/ordersDetail")
	@ResponseBody
	public Map<String, Object> ordersDetail(HttpServletRequest request, HttpServletResponse response,
			String orderNo,String token,String appId,String state) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try{
			if(StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId)){
				UsersMall usersMall = getUsersByTokenAndAppId(token, appId);
				if(usersMall != null){
					if(StringHelper.isNotBlank(orderNo)){
						String userId = usersMall.getId();
						OrdersDetailExample example = new OrdersDetailExample();
						Criteria criteria = example.createCriteria();
						criteria.andIsEffectiveEqualTo(DBConst.TRUE);
						criteria.andOrderNoEqualTo(orderNo);
						// 订单状态（1:待付款，2：已付款，3：待发货，4：待收货，5：已收货，待评价）
						//criteria.andStateEqualTo(state);
						criteria.andUserIdEqualTo(userId);
						List<OrdersDetail> list = ordersDetailService.list(example);
						if(list.size()>0){
							OrderVo Vo = getOrdersDetailByOrderNo(request, response, orderNo, state);
							if(Vo != null){
								resultMap.put(DATA, Vo);
								errorCode = SUCCESS_ERROR_CODE;
								errorMsg = SUCCESS_ERROR_MSG;
							}else{
								errorCode = ORDER_NULL_ERROR_CODE;
								errorMsg = ORDER_NULL_ERROR_MSG;
							}						
						}else{
							errorCode = ORDER_NULL_ERROR_CODE;
							errorMsg = ORDER_NULL_ERROR_MSG;
						}	
					}
				}else {
					errorCode = LOGIN_ERROR_CODE;
					errorMsg = LOGIN_ERROR_MSG;
				}
			}
		}catch(Exception e){
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "ordersDetail", e.toString(), "订单详情", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		return resultMap;
		}
	/**
	 * 根据订单号和订单状态获取订单详细信息
	 * @param request
	 * @param response
	 * @param orderNo
	 * @param state
	 * @return
	 */
	public OrderVo getOrdersDetailByOrderNo(HttpServletRequest request, HttpServletResponse response,
			String orderNo,String state) {
		OrderVo Vo = new OrderVo();
		try {
			Date date = new Date();
			OrdersDetailExample example = new OrdersDetailExample();
			Criteria criteria = example.createCriteria();
			criteria.andIsEffectiveEqualTo(DBConst.TRUE);
			criteria.andOrderNoEqualTo(orderNo);
			// 订单状态（1:待付款，2：已付款，3：待发货，4：待收货，5：已收货，待评价）
			//criteria.andStateEqualTo(state);
			List<OrdersDetail> list = ordersDetailService.list(example);
			if (list.size() > 0) {
				// 订单状态
				String userId = list.get(0).getUserId();
				double actualPay= list.get(0).getActualPay();
				Vo.setPointsAmount(list.get(0).getDeducScore());
				Vo.setPayno(list.get(0).getPayNo());
				Vo.setSystime(date);
				Vo.setState(list.get(0).getState());
				Vo.setPayexpireTime(list.get(0).getPayExpireTime()==null?2:list.get(0).getPayExpireTime());
				Integer ReceiveExpireTime = list.get(0).getReceiveExpireTime();
				if(ReceiveExpireTime != null){
					Vo.setReceiveexpireTime(ReceiveExpireTime);
				}				
				// 收货人信息
				String addresId = list.get(0).getAddressId();
				if (StringHelper.isNotBlank(addresId)) {
					UsersaddressExample examplere = new UsersaddressExample();
					com.itic.mall.system.users.address.persistence.model.UsersaddressExample.Criteria criteriare = examplere
							.createCriteria();
					criteriare.andIdEqualTo(addresId);
					criteriare.andUserIdEqualTo(userId);
					criteriare.andIsEffectiveEqualTo(DBConst.TRUE);
					List<Usersaddress> listre = usersaddressService.list(examplere);
					if (listre.size() > 0) {
						Vo.setReceiverAddress(listre.get(0).getDetail());
						Vo.setReceiverName(listre.get(0).getReceiverName());
						Vo.setReceiverPhone(listre.get(0).getReceiverPhone());
					}
				}
				// 商品信息
				OrdersItemExample exampleg = new OrdersItemExample();
				com.itic.mall.system.orders.item.persistence.model.OrdersItemExample.Criteria criteriag = exampleg
						.createCriteria();
				criteriag.andIsEffectiveEqualTo(DBConst.TRUE);
				criteriag.andOrderNoEqualTo(orderNo);
				//double price = 0;
				List<OrdersItem> listg = ordersItemService.list(exampleg);
				if (listg.size() > 0) { 
					List<GoodsItemVo> listvo = new ArrayList<GoodsItemVo>();
					for (OrdersItem ordersGoodslistg : listg) {
						//开始获取一个商品信息
						String goodsId = ordersGoodslistg.getGoodsId();
						GoodsItemVo goodsItemVo = new GoodsItemVo();						
						goodsItemVo.setOrderNo(orderNo);
						goodsItemVo.setState(ordersGoodslistg.getState());
						goodsItemVo.setGoodsId(goodsId);
						goodsItemVo.setGoodsImg(ordersGoodslistg.getGoodsImg());
						goodsItemVo.setGoodsName(ordersGoodslistg.getGoodsName());
						GoodsDetailVo goodsDetailVo = this.goodsSkuService.getSkuDetailBySkuId(ordersGoodslistg.getSkuId(), 1);
						goodsItemVo.setPrice(goodsDetailVo.getPrice());
						goodsItemVo.setOrginPrice(ordersGoodslistg.getPrice()==null?0:ordersGoodslistg.getPrice());
						goodsItemVo.setCount(ordersGoodslistg.getCount());
						goodsItemVo.setStoreId(ordersGoodslistg.getStoreId());
						Map<String, Object> paramMap =this.goodsSkuService.getGoodSkuById(ordersGoodslistg.getSkuId());// 商品规格信息
						goodsItemVo.setParam(paramMap);//商品规格
						goodsItemVo.setIsSevenBack(ordersGoodslistg.getIsServenBack());
						goodsItemVo.setSkuId(ordersGoodslistg.getSkuId());
						//price = price + ordersGoodslistg.getPrice();
						//添加售后处理状态
					
						OrdersAftersale ordersAftersale =this.ordersAftersaleService.getDealStateByUserIdAndSkuId(userId, ordersGoodslistg.getSkuId(),ordersGoodslistg.getOrderNo());
						if(ordersAftersale!=null){
							goodsItemVo.setDealState(ordersAftersale.getDealState());
							goodsItemVo.setAftersaleId(ordersAftersale.getId());
						}
						else
							goodsItemVo.setDealState("0");
						
						listvo.add(goodsItemVo);
					}
					Vo.setOrderItem(listvo);
				}
				// 红包券
				double couponAmount = 0;
				String couponIds = list.get(0).getCouponId();
				couponAmount = getcouponAmount(couponIds);
				Vo.setCouponAmount(couponAmount);
				
				/*UsersPointslogExample examplep = new UsersPointslogExample();
				examplep.setOrderByClause("reorder desc");
				com.itic.mall.system.users.pointslog.persistence.model.UsersPointslogExample.Criteria criteriap = examplep
						.createCriteria();
				criteriap.andIsEffectiveEqualTo(DBConst.TRUE);
				criteriap.andUserIdEqualTo(userId);
				criteriap.andOrderNoEqualTo(orderNo);
				List<UsersPointslog> listp = usersPointslogService.list(examplep);
				if (listp.size() > 0) {
					Vo.setPointsAmount(listp.get(0).getPointsAmount());					
				}*/
				// 运费，运单编号
				String fee = String.valueOf(list.get(0).getExpressFee());
				if(fee != "null"){
					Vo.setExpressfee(list.get(0).getExpressFee());
				}
				Vo.setExpressNo(list.get(0).getExpressNo());
				OrderExpressExample exampleexp = new OrderExpressExample();
				com.itic.mall.system.orders.express.persistence.model.OrderExpressExample.Criteria criteriaexp = exampleexp.createCriteria();
				criteriaexp.andIsEffectiveEqualTo(DBConst.TRUE);
				if(StringHelper.isNotBlank(list.get(0).getExpressNo())){
					criteriaexp.andExpressNoEqualTo(list.get(0).getExpressNo());
				}
				List<OrderExpress> listexpress = orderExpressService.list(exampleexp);
				if(listexpress.size()>0){
					Vo.setExpressTime(listexpress.get(0).getStartTime());//发货时间
				}
				double expressfee = 0;
				if(list.get(0).getExpressFee() != null)
					expressfee = list.get(0).getExpressFee();
				Vo.setActualpay(actualPay);//订单实付金额
				// 订单底部信息
				Vo.setOrderNo(orderNo);
				/*PayUserlogExample examplepay = new PayUserlogExample();
				com.itic.mall.system.pay.userlog.persistence.model.PayUserlogExample.Criteria criteriapay = examplepay
						.createCriteria();
				criteriapay.andIsEffectiveEqualTo(DBConst.TRUE);
				criteriapay.andOrderNoEqualTo(orderNo);
				List<PayUserlog> listpay = payUserlogService.list(examplepay);*/
				/*if (listpay.size() > 0) {
					Vo.setPaytime(listpay.get(0).getPayTime());
				}*/
				
				Vo.setCreatetime(list.get(0).getCreateTime());				
			}else{
				Vo = null;
			}
		} catch (Exception e) {
			logException("OrdersdetailInterface", "getOrdersDetailByOrderNo", e.toString(), "getOrdersDetailByOrderNo", e);
		}
		return Vo;
	}
	/**
	 * 提醒发货
	 * @param request
	 * @param response
	 * @param orderNo
	 * @param skuId
	 * @return
	 */
	@RequestMapping(value = "/remindsend")
	@ResponseBody
	public Map<String, Object> remindsend(HttpServletRequest request, HttpServletResponse response, String token,String appId,String orderNo,
			String skuId) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		String state = OrderType.Sending.getState();
		String remindState = RemindState.notSend.getState();
		try {
			if(StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId) && StringHelper.isNotBlank(orderNo) && StringHelper.isNotBlank(skuId)){
		    	UsersMall usersMall = getUsersByTokenAndAppId(token,appId);
		    	if(usersMall != null){
		    		String userId = usersMall.getId();
		    		OrdersDetailExample example = new OrdersDetailExample();
					Criteria criteria = example.createCriteria();
					criteria.andIsEffectiveEqualTo(DBConst.TRUE);
					criteria.andOrderNoEqualTo(orderNo);
					criteria.andUserIdEqualTo(userId);
					// 订单状态（1:待付款，2：已付款，3：待发货，4：待收货，5：已收货，待评价）
					//criteria.andStateEqualTo(state);
					List<OrdersDetail> list = ordersDetailService.list(example);
					if(list.size()>0){
						// 商品信息
						OrdersItemExample exampleg = new OrdersItemExample();
						com.itic.mall.system.orders.item.persistence.model.OrdersItemExample.Criteria criteriag = exampleg
								.createCriteria();
						criteriag.andIsEffectiveEqualTo(DBConst.TRUE);
						criteriag.andOrderNoEqualTo(orderNo);
						criteriag.andSkuIdEqualTo(skuId);
						//criteriag.andStateEqualTo(state);
						List<OrdersItem> itemList = ordersItemService.list(exampleg);
						if(itemList.size()>0){
							String itemId = itemList.get(0).getId();
							//记录提醒发货表，只能记录一次，提醒发货之前查是否已经提醒
							OrdersRemindSendExample exampler = new OrdersRemindSendExample();
							com.itic.mall.system.orders.remindsend.persistence.model.OrdersRemindSendExample.Criteria criteriar = exampler.createCriteria();
							criteriar.andIsEffectiveEqualTo(DBConst.TRUE);
							criteriar.andOrderNoEqualTo(orderNo);
							criteriar.andSkuIdEqualTo(skuId);
							criteriar.andUserIdEqualTo(userId);
							criteriar.andOrderItemIdEqualTo(itemId);
							List<OrdersRemindSend> listr = ordersRemindSendService.list(exampler);
							if(listr.size()==0){
								OrdersRemindSend ordersRemindSend = new OrdersRemindSend();
								ordersRemindSend.setUserId(userId);
								ordersRemindSend.setOrderNo(orderNo);
								ordersRemindSend.setOrderItemId(itemId);
								ordersRemindSend.setState(remindState);
								ordersRemindSend.setSkuId(skuId);
								String result = ordersRemindSendService.add(ordersRemindSend);
								if(SUCCESS.equals(result)){
									errorCode = SUCCESS_ERROR_CODE;
									errorMsg = SUCCESS_ERROR_MSG;
								}
							}else{
								errorCode = ORDER_ADD_REMIND_SEND_ERROR;
								errorMsg = ORDER_ADD_REMIND_SEND_MSG;
							}							
						}else{
							errorCode = ORDER_ITEM_ERROR_CODE;
							errorMsg = ORDER_ITEM_ERROR_MSG;
						}
					}else{
						errorCode = ORDER_SEND_STATE_ERROR;
						errorMsg = ORDER_SEND_STATE_MSG;
					}
		    	}else{
		    		errorCode = LOGIN_ERROR_CODE;
			       	errorMsg = LOGIN_ERROR_MSG;
		    	}
			}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "expressdetail", e.toString(), "物流详情", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}
	/**
	 * 物流详情
	 * 
	 * @param request
	 * @param response
	 * @param token
	 * @param appId
	 * @return
	 */
	@RequestMapping(value = "/expressdetail")
	@ResponseBody
	public Map<String, Object> expressdetail(HttpServletRequest request, HttpServletResponse response, String orderNo,String skuId) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			if (StringHelper.isNotBlank(orderNo) && StringHelper.isNotBlank(skuId)) {
				OrdersItemExample exampleorder = new OrdersItemExample();
				com.itic.mall.system.orders.item.persistence.model.OrdersItemExample.Criteria criteriaorder = exampleorder.createCriteria();
				criteriaorder.andIsEffectiveEqualTo(DBConst.TRUE);
				criteriaorder.andOrderNoEqualTo(orderNo);
				criteriaorder.andGoodsIdEqualTo(skuId);
				criteriaorder.andStateEqualTo("4");// 待收货
				List<OrdersItem> listorder = ordersItemService.list(exampleorder);
				if (listorder.size() > 0) {
					OrderExpressExample example = new OrderExpressExample();
					com.itic.mall.system.orders.express.persistence.model.OrderExpressExample.Criteria criteria = example
							.createCriteria();
					criteria.andIsEffectiveEqualTo(DBConst.TRUE);
					criteria.andOrderNoEqualTo(orderNo);
					criteria.andSkuIdEqualTo(skuId);
					List<OrderExpress> list = orderExpressService.list(example);
					if (list != null && list.size() > 0) {
						resultMap.put(DATA, ValueHelper.tranList2MapList(list, ignoreProperties));
						errorCode = SUCCESS_ERROR_CODE;
						errorMsg = SUCCESS_ERROR_MSG;
					} else {
						errorCode = EXPRESS_ERROR_CODE;
						errorMsg = EXPRESS_ERROR_MSG;
					}
				} else {
					errorCode = ORDER_ERROR_CODE;
					errorMsg = ORDER_ERROR_MSG;
				}
			}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "expressdetail", e.toString(), "物流详情", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}
	
	/**
	 * 根据订单号获取订单状态
	 * @param orderNo
	 * @return
	 */
	public String getOrderStateByOrderNo(String orderNo){
		String state = null;
		if(StringHelper.isNotBlank(orderNo)){
			//订单信息
			OrdersDetailExample example = new OrdersDetailExample();
			com.itic.mall.system.orders.detail.persistence.model.OrdersDetailExample.Criteria criteria = example.createCriteria();
			criteria.andIsEffectiveEqualTo(DBConst.TRUE);
			criteria.andOrderNoEqualTo(orderNo);
			List<OrdersDetail> list = ordersDetailService.list(example);
			if(list.size()>0){
				state = list.get(0).getState();//订单状态（1:待付款，2：已付款，3：待发货，4：待收货，5：已收货，待评价）
			}
		}
		return state;
	}
	
	/**
	 * 申请售后初始化
	 * 
	 * @param request
	 * @param response
	 * @param token
	 * @param appId
	 * @return
	 */
	@RequestMapping(value = "/applyindex")
	@ResponseBody
	public Map<String, Object> applyindex(HttpServletRequest request, HttpServletResponse response, String token,String appId,String orderNo,String skuId) {
		Map<String, Object> resultMap = new HashMap<>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			if(StringUtils.isNoneBlank(appId,token,orderNo,skuId)) {
				UsersMall usersMall = this.getUsersByTokenAndAppId(token, appId);
				if(usersMall!=null) {
					GoodsSpu goodsSpu = this.goodsSpuService.getBySku(skuId);
					if(goodsSpu !=null) {
						GoodsDetailVo goodsDetailVo = new GoodsDetailVo();
						AfterSaleVo afterSaleVo = new AfterSaleVo();
						afterSaleVo.setUserId(usersMall.getId());
						OrdersDetail ordersDetail = this.ordersDetailService.getOrdersDetailByOrderNo(orderNo);
						double expressFee = ordersDetail.getExpressFee()==null?0:ordersDetail.getExpressFee();
						afterSaleVo.setExpressFee(expressFee);
						OrdersItem ordersItem = this.ordersItemService.getOrdersItemBySpuIdAndOrderNo(skuId, orderNo);
						if(ordersItem!=null) {
							goodsDetailVo.setGoodsId(ordersItem.getGoodsId());
							goodsDetailVo.setGoodsImg(ordersItem.getGoodsImg());
							goodsDetailVo.setCount(ordersItem.getCount());
							goodsDetailVo.setGoodsImg(ordersItem.getGoodsImg());
							goodsDetailVo.setGoodsName(ordersItem.getGoodsName());
							
							goodsDetailVo.setOrginPrice(ordersItem.getOrginPrice()==null?0:ordersItem.getOrginPrice());
							goodsDetailVo.setPrice(ordersItem.getPrice()==null?0:ordersItem.getPrice());
							//商品规格属性
							Map<String, Object> property = this.goodsSkuService.getGoodSkuById(skuId);
							goodsDetailVo.setParam(property);
							int totalCount =ordersItem.getCount()==null?0:ordersItem.getCount();
							afterSaleVo.setState(ordersItem.getState());
							afterSaleVo.setGoodsDetailVo(goodsDetailVo);
							double sumAmount =ordersItem.getActualPay();
							afterSaleVo.setSumAmount(sumAmount);
							afterSaleVo.setTotalCount(totalCount);
							// 计算退款金额
							double refundAmount = ordersItem.getActualPay() - (ordersItem.getCouponPrice()==null?0:ordersItem.getCouponPrice());
							//double refundAmount = this.ordersItemService.calRefund(orderNo, skuId);
							
							afterSaleVo.setRefundAmount(refundAmount);
						}
						resultMap.put(DATA, afterSaleVo);
						errorCode = SUCCESS_ERROR_CODE;
						errorMsg = SUCCESS_ERROR_MSG;
					}
				}else {
					errorCode = LOGIN_ERROR_CODE;
			       	errorMsg = LOGIN_ERROR_MSG;
				}
			}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "applyindex", e.toString(), "申请售后初始化", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}
	
	/**
	 * 仅退款售后申请
	 * 
	 * @param request
	 * @param response
	 * @param token
	 * @param appId
	 * @return
	 */
	@RequestMapping(value = "/addRefundapply")
	@ResponseBody
	public Map<String, Object> addRefundapply(HttpServletRequest request, HttpServletResponse response,String token,String appId, String orderNo,String goodsId,
			String expressState,String refundReason,double refundAmount,String img,String content) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		String typeMsg = "";
		String fee = String.valueOf(refundAmount);
		String type = "1";
		typeMsg = AFTER_SALE_APPLY_REFUND_MSG;
		try {
			if (StringHelper.isNotBlank(token)&& StringHelper.isNotBlank(appId) && StringHelper.isNotBlank(goodsId) && StringHelper.isNotBlank(orderNo) 
					&& StringHelper.isNotBlank(type) && StringHelper.isNotBlank(expressState) 
					&& StringHelper.isNotBlank(refundReason) && StringHelper.isNotBlank(fee) && StringHelper.isNotBlank(content)) {
				UsersMall usersMall = getUsersByTokenAndAppId(token, appId);
				if(usersMall != null){
					String userId = usersMall.getId();
					OrdersAftersale model = new OrdersAftersale();
					model.setUserId(userId);
					model.setOrderNo(orderNo);
					model.setGoodsId(goodsId);
					model.setType(type);
					model.setExpressState(expressState);
					model.setApplyReason(refundReason);
					model.setRefunfAmount(refundAmount);
					model.setImg(img);
					model.setContent(content);
					String result = ordersAftersaleService.add(model);// 提交售后申请
					Date d = new Date();
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					String dateNowStr = sdf.format(d);
					System.out.println("格式化后的日期：" + dateNowStr);
					if (SUCCESS.equals(result)) {
						//添加售后成功后，要将订单状态改为退款中
						//订单状态（1:待付款，2：已付款，3：待发货，4：待收货，5：已收货，待评价，6：换货中，7：换货成功，8：退货中，9：退货成功，10：维修中，11：维修成功，12：退款中，13：退款成功）
						OrdersDetail ordersDetail = getOrderByAfterState(orderNo,"1");
						ordersDetail.setState("12");
						result = ordersDetailService.edit(ordersDetail);
						if(SUCCESS.equals(result)){
							resultMap.put(AFTER_SALE_APPLY_TIME, dateNowStr);
							resultMap.put(AFTER_SALE_APPLY_TYPE, typeMsg);
							errorMsg = AFTER_SALE_SUCCESS_APPLY_RESULT;
							errorCode = SUCCESS_ERROR_CODE;
						}
					}
				}else{
					errorCode = LOGIN_ERROR_CODE;
			       	errorMsg = LOGIN_ERROR_MSG;
				}
				
			}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "addRefundapply", e.toString(), "售后申请", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}
	/**
	 * 添加售后申请
	 * @param request
	 * @param response
	 * @param userId
	 * @param orderNo
	 * @param goodsId
	 * @param type
	 * @param refundReason
	 * @param refundAmount
	 * @param img
	 * @param content
	 * @return
	 */
	@RequestMapping(value = "/addafterSaleapply")
	@ResponseBody
	public Map<String, Object> addReturnGoodsapply(HttpServletRequest request, HttpServletResponse response,String token,String appId, String orderNo,String skuId,
			String reason,Double amount,String img,String content,String type,Integer count,Double fee) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		String typeMsg = AFTER_SALE_APPLY_CANCEL_MSG;
		try{
			AfterSaleType afterSaleType  =null;
			if(StringUtils.isNoneBlank(token,appId,orderNo,skuId,reason,type) && (afterSaleType = AfterSaleType.getType(type))!=null) {
				UsersMall usersMall = this.getUsersByTokenAndAppId(token, appId);
				if(usersMall!=null) {
					OrdersItem ordersItem = this.ordersItemService.getOrdersItemBySpuIdAndOrderNo(skuId, orderNo);
					OrdersAftersale ordersAftersale = this.ordersAftersaleService.getDealStateByUserIdAndSkuId(usersMall.getId(), ordersItem.getSkuId(), ordersItem.getOrderNo());
					if(ordersAftersale ==null) {
						String userId = usersMall.getId();
						OrdersAftersale model = new OrdersAftersale();
						model.setUserId(userId);
						model.setOrderNo(orderNo);
						model.setGoodsId(skuId);
						model.setContent(content);
						model.setCount(count==null?ordersItem.getCount():count);
						model.setImg(img);
						model.setOrderOldState(ordersItem.getState());
						model.setType(afterSaleType.getState());
						//问题类型(1:仅退款，2：换货，3：退款退货，4：维修)
						model.setApplyReason(reason);
						if(amount != null)
							model.setRefunfAmount(amount);
						model.setDealState(AfterSaleDealType.Pending.getState());
						this.ordersAftersaleService.add(model);
						OrdersDetail ordersDetail = this.ordersDetailService.getOrdersDetailByOrderNo(orderNo);
						//GoodsSpu goodsSpu = this.goodsSpuService.getBySku(skuId);
						switch (afterSaleType) {
							case change:
								//ordersDetail.setState(OrderType.Refunding.getState());
								ordersItem.setState(OrderType.Refunding.getState());
								break;
							case cance:
								//ordersDetail.setState(OrderType.Exchangeing.getState());
								ordersItem.setState(OrderType.Exchangeing.getState());
								break;
							case fix:
								//ordersDetail.setState(OrderType.ReturnGoodsing.getState());
								ordersItem.setState(OrderType.ReturnGoodsing.getState());
								break;
							case refund:
								//ordersDetail.setState(OrderType.Repairing.getState());
								ordersItem.setState(OrderType.Repairing.getState());
								break;
							default:
								break;
						}
						//TODO  申请售后处理订单 减少生息钱 
						ordersDetail.setLivingType("0");
						this.ordersDetailService.edit(ordersDetail);
						FinanceUserMakeMoneyLog financeUserMakeMoneyLog  = this.financeUserMakeMoneyLogService.getMakeMoneyLogByOrderNo(ordersDetail.getOrderNo(), usersMall.getId());
						if(financeUserMakeMoneyLog!=null) {
							double livingMoney = usersMall.getLivingMoney()==null?0:usersMall.getLivingMoney();
							double subMoney = financeUserMakeMoneyLog.getMoney()==null?0:financeUserMakeMoneyLog.getMoney();
							livingMoney = livingMoney -subMoney;
							livingMoney = livingMoney <=0?0:livingMoney;
							usersMall.setLivingMoney(livingMoney);
							this.usersMallService.edit(usersMall);
							financeUserMakeMoneyLog.setIsLiving("0");
							this.financeUserMakeMoneyLogService.edit(financeUserMakeMoneyLog);
						}
						this.ordersItemService.edit(ordersItem);
						String dateNowStr = DateHelper.getDate();
						resultMap.put(AFTER_SALE_APPLY_TIME, dateNowStr);
						resultMap.put(AFTER_SALE_APPLY_TYPE, typeMsg);
						errorMsg = AFTER_SALE_SUCCESS_APPLY_RESULT;
						errorCode = SUCCESS_ERROR_CODE;
					}else {
						errorCode = ORDER_AFTERSALE_ALREADY_CODE;
				       	errorMsg = ORDER_AFTERSALE_ALREADY_MSG;
					}
				}else {
					errorCode = LOGIN_ERROR_CODE;
			       	errorMsg = LOGIN_ERROR_MSG;
				}
			}
		}catch(Exception e){
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "addafterSaleapply", e.toString(), "添加售后申请", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		return resultMap;
		}
	/**
	 * 添加换货售后申请
	 * @param request
	 * @param response
	 * @param userId
	 * @param orderNo
	 * @param goodsId
	 * @param fixReason
	 * @param img
	 * @param content
	 * @return
	 */
	@RequestMapping(value = "/addChangeapply")
	@ResponseBody
	public Map<String, Object> addChangeapply(HttpServletRequest request, HttpServletResponse response,String userId, String orderNo,String goodsId,
			String chgReason,String img,String content) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		String typeMsg = AFTER_SALE_APPLY_CHANGE_MSG;
		String type = "3";//问题类型(1：仅退款，2:退款退货，3：换货，4：维修)
		try{
			if (StringHelper.isNotBlank(goodsId) && StringHelper.isNotBlank(userId)&&StringHelper.isNotBlank(orderNo) 
					&& StringHelper.isNotBlank(chgReason)
					&& StringHelper.isNotBlank(content)) {
				OrdersAftersale model = new OrdersAftersale();
				model.setUserId(userId);
				model.setOrderNo(orderNo);
				model.setGoodsId(goodsId);
				model.setType(type);
				model.setApplyReason(chgReason);
				model.setImg(img);
				model.setContent(content);
				String result = ordersAftersaleService.add(model);// 提交售后申请
				Date d = new Date();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				String dateNowStr = sdf.format(d);
				System.out.println("格式化后的日期：" + dateNowStr);
				if (SUCCESS.equals(result)) {
					//添加售后成功后，要将订单状态改为退款中
					//订单状态（1:待付款，2：已付款，3：待发货，4：待收货，5：已收货，待评价，6：换货中，7：换货成功，8：退货中，9：退货成功，10：维修中，11：维修成功，12：退款中，13：退款成功）
					OrdersDetail ordersDetail = getOrderByAfterState(orderNo,"1");
					ordersDetail.setState("6");
					result = ordersDetailService.edit(ordersDetail);
					if(SUCCESS.equals(result)){
						resultMap.put(AFTER_SALE_APPLY_TIME, dateNowStr);
						resultMap.put(AFTER_SALE_APPLY_TYPE, typeMsg);
						errorMsg = AFTER_SALE_SUCCESS_APPLY_RESULT;
						errorCode = SUCCESS_ERROR_CODE;
					}
				}
			}
		}catch(Exception e){
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "addChangeapply", e.toString(), "添加换货售后申请", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		return resultMap;
		}
	/**
	 * 维修售后申请
	 * @param request
	 * @param response
	 * @param userId
	 * @param orderNo
	 * @param goodsId
	 * @param refundReason
	 * @param refundAmount
	 * @param img
	 * @param content
	 * @return
	 */
	@RequestMapping(value = "/addFixapply")
	@ResponseBody
	public Map<String, Object> addFixapply(HttpServletRequest request, HttpServletResponse response,String userId, String orderNo,String goodsId,
			String fixReason,String img,String content) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		String typeMsg = AFTER_SALE_APPLY_FIX_MSG;
		String type = "4";//问题类型(1：仅退款，2:退款退货，3：换货，4：维修)
		try{
			if (StringHelper.isNotBlank(goodsId) && StringHelper.isNotBlank(userId)&&StringHelper.isNotBlank(orderNo) 
					&& StringHelper.isNotBlank(fixReason) && StringHelper.isNotBlank(content)) {
				//根据订单号和商品号获取该商品数量个数
				int count = getCountByOrderNoandgoodsId(orderNo,goodsId);
				OrdersAftersale model = new OrdersAftersale();
				model.setUserId(userId);
				model.setOrderNo(orderNo);
				model.setGoodsId(goodsId);
				model.setType(type);
				model.setApplyReason(fixReason);
				model.setImg(img);
				model.setCount(count);
				model.setContent(content);
				String result = ordersAftersaleService.add(model);// 提交售后申请
				Date d = new Date();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				String dateNowStr = sdf.format(d);
				System.out.println("格式化后的日期：" + dateNowStr);
				if (SUCCESS.equals(result)) {
					//添加售后成功后，要将订单状态改为退款中
					//订单状态（1:待付款，2：已付款，3：待发货，4：待收货，5：已收货，待评价，6：换货中，7：换货成功，8：退货中，9：退货成功，10：维修中，11：维修成功，12：退款中，13：退款成功）
					OrdersDetail ordersDetail = getOrderByAfterState(orderNo,"1");
					ordersDetail.setState("10");
					result = ordersDetailService.edit(ordersDetail);
					if(SUCCESS.equals(result)){
						resultMap.put(AFTER_SALE_APPLY_TIME, dateNowStr);
						resultMap.put(AFTER_SALE_APPLY_TYPE, typeMsg);
						errorMsg = AFTER_SALE_SUCCESS_APPLY_RESULT;
						errorCode = SUCCESS_ERROR_CODE;
					}
				}
			}
		}catch(Exception e){
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "addFixapply", e.toString(), "维修售后申请", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		return resultMap;
		}
	/**
	 * 获取售后详情
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/getapplyDetail")
	@ResponseBody
	public Map<String, Object> getapplyDetail(HttpServletRequest request, HttpServletResponse response,String aftersaleId) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try{
			if(StringHelper.isNotBlank(aftersaleId)){
				OrdersAftersaleExample example = new OrdersAftersaleExample();
				com.itic.mall.system.orders.aftersale.persistence.model.OrdersAftersaleExample.Criteria criteria = example
						.createCriteria();
				criteria.andIsEffectiveEqualTo(DBConst.TRUE);
				criteria.andIdEqualTo(aftersaleId);
				List<OrdersAftersale> list = ordersAftersaleService.list(example);
				if(list.size()>0){
					String state = list.get(0).getDealState();
					AfterSaleDealVo afterSaleDealVo = new AfterSaleDealVo();
					String desc = getDescribeByState(state);
					afterSaleDealVo.setState(state);
					afterSaleDealVo.setExpireTime(list.get(0).getExpireTime()==null?0:list.get(0).getExpireTime());

					afterSaleDealVo.setContent(desc);
					double amount = list.get(0).getRefunfAmount()==null?0:list.get(0).getRefunfAmount();
					afterSaleDealVo.setRefundAmount(amount);
					String goodsId = list.get(0).getGoodsId();
					String orderNo = list.get(0).getOrderNo();
					//根据订单号和商品ID获取商品数量
					int count = getCountByOrderNoandgoodsId(orderNo,goodsId);
					GoodsDetailVo goodsDetailVo = getGoodsDetailByOrderNoandgoodsId(orderNo, goodsId);
					afterSaleDealVo.setGoodsDetailVo(goodsDetailVo);
					afterSaleDealVo.setReason(list.get(0).getApplyReason());
					afterSaleDealVo.setApplycount(count);
					afterSaleDealVo.setApplyTime(list.get(0).getCreateTime());
					afterSaleDealVo.setReturnGoodsNo(list.get(0).getReturnGoodsNo());
					resultMap.put(DATA, afterSaleDealVo);
					errorCode = SUCCESS_ERROR_CODE;
					errorMsg = SUCCESS_ERROR_MSG;
				}
			}
		}catch(Exception e){
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "getapplyDetail", e.toString(), "获取售后详情", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		return resultMap;
		}
	/**
	 * 初始化修改售后申请
	 * @param request
	 * @param response
	 * @param aftersaleId
	 * @return
	 */
	@RequestMapping(value = "/initEditApplyDetail")
	@ResponseBody
	public Map<String, Object> initEditApplyDetail(HttpServletRequest request, HttpServletResponse response,String aftersaleId) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try{
			if(StringHelper.isNotBlank(aftersaleId)){
				OrdersAftersaleExample example = new OrdersAftersaleExample();
				com.itic.mall.system.orders.aftersale.persistence.model.OrdersAftersaleExample.Criteria criteria = example
						.createCriteria();
				criteria.andIsEffectiveEqualTo(DBConst.TRUE);
				criteria.andIdEqualTo(aftersaleId);
				List<OrdersAftersale> list = ordersAftersaleService.list(example);
				if(list.size()>0){
					String goodsId = list.get(0).getGoodsId();
					String orderNo = list.get(0).getOrderNo();
					AfterSaleEditVo afterSaleEditVo = new AfterSaleEditVo();
					//根据订单号获取售后类型可展示项
					//根据订单号和商品ID获取订单物流状态，若已收货，则展示换货，退款退货，维修，否则只展示仅退款和退款退货
					String orderstate = getOrderStateByOrderNo(orderNo);
					//订单状态（1:待付款，2：已付款，3：待发货，4：待收货，5：已收货，待评价，6：换货中，7：换货成功，8：退货中，9：退货成功，10：维修中，11：维修成功，12：退款中，13：退款成功）
					if(StringHelper.isNotBlank(orderstate)){
						if(orderstate.equals("2") || orderstate.equals("3") || orderstate.equals("5")){
							//用户还未收到货只展示进退款和退款退货
							afterSaleEditVo.setIsShowRefund(DBConst.TRUE);
						}
						if(orderstate.equals("5")){
							//用户已收货展示换货，退款退货，维修
							afterSaleEditVo.setIsShowCancel(DBConst.TRUE);
							afterSaleEditVo.setIsShowChange(DBConst.TRUE);
							afterSaleEditVo.setIsShowFix(DBConst.TRUE);
							//货物状态（001：未收货，002：已收货，003：未发货）
							afterSaleEditVo.setExpressState("002");
						}
					}
					afterSaleEditVo.setType(list.get(0).getType());
					//根据商品号和订单号获取商品信息
					GoodsDetailVo goodsDetailVo = getGoodsDetailByOrderNoandgoodsId(orderNo,goodsId);
					afterSaleEditVo.setGoodsDetailVo(goodsDetailVo);
					afterSaleEditVo.setIsShowCancel(list.get(0).getIsShowCancel());
					afterSaleEditVo.setIsShowChange(list.get(0).getIsShowChange());
					afterSaleEditVo.setIsShowFix(list.get(0).getIsShowFix());
					afterSaleEditVo.setIsShowRefund(list.get(0).getIsShowRefund());
					afterSaleEditVo.setExpressState(list.get(0).getExpressState());
					afterSaleEditVo.setReason(list.get(0).getApplyReason());
					String fee = String.valueOf(list.get(0).getRefunfAmount());
					if(fee != "null"){
						afterSaleEditVo.setRefundAmount(list.get(0).getRefunfAmount());
					}
					afterSaleEditVo.setImg(list.get(0).getImg());
					afterSaleEditVo.setContent(list.get(0).getContent());
					resultMap.put(DATA, afterSaleEditVo);
					errorCode = SUCCESS_ERROR_CODE;
					errorMsg = SUCCESS_ERROR_MSG;
				}
			}
		
		}catch(Exception e){
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "initEditApplyDetail", e.toString(), "初始化修改售后申请", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		return resultMap;
		}
	/**
	 * 编辑修改售后申请
	 * @param request
	 * @param response
	 * @param aftersaleId
	 * @return
	 */
	@RequestMapping(value = "/editApplyDetail")
	@ResponseBody
	public Map<String, Object> editApplyDetail(HttpServletRequest request, HttpServletResponse response,String orderNo,String aftersaleId,String type,String expressState,String reason,
			String content,String img) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try{
			if(StringHelper.isNotBlank(aftersaleId) && StringHelper.isNotBlank(orderNo)){
				OrdersAftersaleExample example = new OrdersAftersaleExample();
				com.itic.mall.system.orders.aftersale.persistence.model.OrdersAftersaleExample.Criteria criteria = example
						.createCriteria();
				criteria.andIsEffectiveEqualTo(DBConst.TRUE);
				criteria.andIdEqualTo(aftersaleId);
				criteria.andOrderNoEqualTo(orderNo);
				List<OrdersAftersale> list = ordersAftersaleService.list(example);
				if(list.size()>0){
					OrdersAftersale ordersAftersale = list.get(0);
					ordersAftersale.setType(type);
					ordersAftersale.setExpressState(expressState);
					ordersAftersale.setApplyReason(reason);
					ordersAftersale.setContent(content);
					ordersAftersale.setImg(img);
					String result = ordersAftersaleService.edit(ordersAftersale);
					if(SUCCESS.equals(result)){
						errorCode = SUCCESS_ERROR_CODE;
						errorMsg = SUCCESS_ERROR_MSG;
					}
				}else{
					errorCode = ORDER_ERROR_CODE;
					errorMsg = ORDER_ERROR_MSG;
				}
			}
		}catch(Exception e){
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "editApplyDetail", e.toString(), "编辑修改售后申请", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		return resultMap;
		}
	/**
	 * 撤销申请
	 * @param request
	 * @param response
	 * @param aftersaleId
	 * @return
	 */
	@RequestMapping(value = "/delApplyDetail")
	@ResponseBody
	public Map<String, Object> delApplyDetail(HttpServletRequest request, HttpServletResponse response,String token,String appId,String afterSafeId) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			if(StringUtils.isNoneBlank(token,appId)) {
				UsersMall usersMall = this.getUsersByTokenAndAppId(token, appId);
				if(usersMall !=null) {
					//获取用户未过期的优惠券
					OrdersAftersale aftersale =  this.ordersAftersaleService.get(afterSafeId);
					AfterSaleDealType afterSaleDealType = AfterSaleDealType.getType(aftersale.getDealState());
					switch (afterSaleDealType) {
						case Refunding:
						case RefundClose:
						case AgreeRefund:
						case RefundSuccess:
							// 提示订单处理中，不能撤销
							errorCode = AFTERSALE_ALREADY_PENDING_ERROR_CODE;
							errorMsg = AFTERSALE_ALREADY_PENDING_ERROR_MSG;
							break;
						case Pending:
						case Refuse:
						case CanceAlpply:
							aftersale.setDealState(AfterSaleDealType.CanceAlpply.getState());
							this.ordersAftersaleService.edit(aftersale);
							OrdersItem ordersItem = this.ordersItemService.getOrdersItemBySpuIdAndOrderNo(aftersale.getGoodsId(), aftersale.getOrderNo());
							ordersItem.setState(aftersale.getOrderOldState());
							String desc = getDescribeByState(AfterSaleDealType.CanceAlpply.getState());
							resultMap.put("remindMsg", desc);
							errorCode = SUCCESS_ERROR_CODE;
							errorMsg = SUCCESS_ERROR_MSG;
							break;
					}
				}else{
					// 提示登录失效
					errorCode = PARAM_ERROR_CODE;
					errorMsg = PARAM_ERROR_MSG;
				}
			}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "canceAfterSale", e.toString(), "撤销售后申请", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
}
	/**
	 * 初始化填写物流信息
	 * @param request
	 * @param response
	 * @param aftersaleId
	 * @return
	 */
	@RequestMapping(value = "/initaddexpress")
	@ResponseBody
	public Map<String, Object> initaddexpress(HttpServletRequest request, HttpServletResponse response,String aftersaleId) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try{
			if(StringHelper.isNotBlank(aftersaleId)){
				OrdersAftersaleExample example = new OrdersAftersaleExample();
				com.itic.mall.system.orders.aftersale.persistence.model.OrdersAftersaleExample.Criteria criteria = example
						.createCriteria();
				criteria.andIsEffectiveEqualTo(DBConst.TRUE);
				criteria.andIdEqualTo(aftersaleId);
				List<OrdersAftersale> list = ordersAftersaleService.list(example);
				if(list.size()>0){
					if(list.get(0).getType().equals("2") || list.get(0).getType().equals("3")){
						String orderNo = list.get(0).getOrderNo();
						String goodsId = list.get(0).getGoodsId();
						//根据订单号和商品ID获取商品信息
						GoodsDetailVo goodsDetailVo = getGoodsDetailByOrderNoandgoodsId(orderNo,goodsId);
						resultMap.put(DATA, goodsDetailVo);
						errorCode = SUCCESS_ERROR_CODE;
						errorMsg = SUCCESS_ERROR_MSG;
					}else{
						errorCode = AFTERSALE_TYPE_EXPRESS_ERROR_CODE;
						errorMsg = AFTERSALE_TYPE_EXPRESS_ERROR_MSG;
					}
				}else{
					errorCode = AFTERSALE_ERROR_CODE;
					errorMsg = AFTERSALE_ERROR_MSG;
				}
			}
		}catch(Exception e){
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "initaddexpress", e.toString(), "初始化填写物流信息", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		return resultMap;
		}
	/**
	 * 获取物流公司信息列表
	 * @param request
	 * @param response
	 * @param aftersaleId
	 * @return
	 */
	@RequestMapping(value = "/getexpress")
	@ResponseBody
	public Map<String, Object> getexpress(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try{
			List<Map<String,Object>> list = getexpresslist(request, response);
			if(list.size()>0){
				resultMap.put(DATA, list);
				errorCode = SUCCESS_ERROR_CODE;
				errorMsg = SUCCESS_ERROR_MSG;
			}
		}catch(Exception e){
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "addexpress", e.toString(), "填写物流信息", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		return resultMap;
		}
	/**
	 * 添加物流信息
	 * @param request
	 * @param response
	 * @param aftersaleId
	 * @return
	 */
	@RequestMapping(value = "/addexpress")
	@ResponseBody
	public Map<String, Object> addexpress(HttpServletRequest request, HttpServletResponse response,String aftersaleId,String expcompName,String expcompNo,String expressNo,String userPhone) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try{
			if(StringHelper.isNotBlank(aftersaleId)){
				OrdersAftersaleExample example = new OrdersAftersaleExample();
				com.itic.mall.system.orders.aftersale.persistence.model.OrdersAftersaleExample.Criteria criteria = example
						.createCriteria();
				criteria.andIsEffectiveEqualTo(DBConst.TRUE);
				criteria.andIdEqualTo(aftersaleId);
				List<OrdersAftersale> list = ordersAftersaleService.list(example);
				if(list.size()>0){
					OrdersAftersale ordersAftersale = list.get(0);
					ordersAftersale.setExpressCompanyName(expcompName);
					ordersAftersale.setExpressCompanyNo(expressNo);
					ordersAftersale.setUserPhone(userPhone);
					ordersAftersale.setExpressNo(expressNo);
					String result = ordersAftersaleService.edit(ordersAftersale);
					if(SUCCESS.equals(result)){
						errorCode = SUCCESS_ERROR_CODE;
						errorMsg = SUCCESS_ERROR_MSG;
					}
				}else{
					errorCode = AFTERSALE_ERROR_CODE;
					errorMsg = AFTERSALE_ERROR_MSG;
				}
			}
		}catch(Exception e){
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "addexpress", e.toString(), "填写物流信息", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		return resultMap;
		}
	/**
	 * 添加评论
	 * 
	 * @param request
	 * @param response
	 * @param orderId
	 * @param judgelev
	 * @param content
	 * @param desclev
	 * @param tranlev
	 * @param servlev
	 * @return
	 */
	@RequestMapping(value = "/addjudge")
	@ResponseBody
	public Map<String, Object> addjudge(HttpServletRequest request, HttpServletResponse response, String orderNo,
			Integer judgelev, String content, Integer desclev, Integer tranlev, Integer servlev) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			if (StringHelper.isNotBlank(orderNo)) {
				OrdersDetailExample example = new OrdersDetailExample();
				Criteria criteria = example.createCriteria();
				criteria.andIsEffectiveEqualTo(DBConst.TRUE);
				criteria.andOrderNoEqualTo(orderNo);
				criteria.andStateEqualTo("5");// 订单状态（1:待付款，2：已付款，3：待发货，4：待收货，5：已收货，待评价）
				List<OrdersDetail> list = ordersDetailService.list(example);
				if (list.size() > 0) {
					if (StringHelper.isNotBlank(content) && judgelev != null && desclev != null && tranlev != null
							&& servlev != null) {
						GoodsJudge model = new GoodsJudge();
						model.setOrderId(orderNo);
						model.setDescribeLevel(desclev);
						model.setJudgeLevel(judgelev);
						model.setContent(content);
						model.setTransLevel(tranlev);
						model.setServeLevel(servlev);
						String result = goodsJudgeService.add(model);
						if (SUCCESS.equals(result)) {
							errorCode = SUCCESS_ERROR_CODE;
							errorMsg = SUCCESS_ERROR_MSG;
						}
					}
				} else {
					errorCode = ORDER_ERROR_CODE;
					errorMsg = ORDER_ERROR_MSG;
				}
			}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "addjudge", e.toString(), "添加评论", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}

	/**
	 * 使用满减券
	 * 
	 * @param request
	 * @param response
	 * @param token
	 * @param appId
	 * @return
	 */
	@RequestMapping(value = "/usecoupon")
	@ResponseBody
	public Map<String, Object> usecoupon(HttpServletRequest request, HttpServletResponse response, String token,
			String appId, String orderNo, String couponId) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			UsersMall usersMall = getUsersByTokenAndAppId(token, appId);
			if (usersMall != null) {
				if (StringHelper.isNotBlank(orderNo) && StringHelper.isNotBlank(couponId)) {
					Date date = new Date();
					String userId = usersMall.getId();
					OrdersDetailExample example = new OrdersDetailExample();
					com.itic.mall.system.orders.detail.persistence.model.OrdersDetailExample.Criteria criteria = example
							.createCriteria();
					criteria.andIsEffectiveEqualTo(DBConst.TRUE);
					criteria.andOrderNoEqualTo(orderNo);
					criteria.andUserIdEqualTo(userId);
					criteria.andStateEqualTo("1");
					List<OrdersDetail> list = ordersDetailService.list(example);
					UsersCouponExample exampleuc = new UsersCouponExample();
					com.itic.mall.system.users.usercoupon.persistence.model.UsersCouponExample.Criteria criteriauc = exampleuc
							.createCriteria();
					criteriauc.andIsEffectiveEqualTo(DBConst.TRUE);
					criteriauc.andCouponIdEqualTo(couponId);
					criteriauc.andStartTimeLessThan(date);
					criteriauc.andEndTimeGreaterThan(date);
					criteriauc.andTypeEqualTo("001");// 满减券
					criteriauc.andIsUsedEqualTo(DBConst.FALSE);
					List<UsersCoupon> usersCoupon = usersCouponService.list(exampleuc);
					if (list.size() > 0 && usersCoupon.size() > 0) {
						// 商品信息
						Map<String, Object> goodsMap = new HashMap<String, Object>();
						OrdersItemExample examplegoods = new OrdersItemExample();
						com.itic.mall.system.orders.item.persistence.model.OrdersItemExample.Criteria criteriagoods = examplegoods
								.createCriteria();
						criteriagoods.andIsEffectiveEqualTo(DBConst.TRUE);
						criteriagoods.andOrderNoEqualTo(orderNo);
						List<OrdersItem> listgoods = ordersItemService.list(examplegoods);
						// 查看该订单是否适用于此红包券。先获取红包券ID和该订单所属的商家ID和商品ID
						String ordstorId = listgoods.get(0).getStoreId();
						String ordgoodsId = listgoods.get(0).getGoodsId();
						double sumAmount = list.get(0).getSumAmount();// 使用红包前的金额
						double useCond = usersCoupon.get(0).getUseCond();
						double amount = usersCoupon.get(0).getAmount();// 红包券金额
						// 如果总金额大于使用条件金额
						if (sumAmount >= useCond) {
							// 1.获取红包券适用的商家和商品
							GoodsCouponExample exampleg = new GoodsCouponExample();
							com.itic.mall.system.goods.coupon.persistence.model.GoodsCouponExample.Criteria criteriag = exampleg
									.createCriteria();
							criteriag.andIsEffectiveEqualTo(DBConst.TRUE);
							criteriag.andCouponIdEqualTo(couponId);
							criteriag.andGoodsIdEqualTo(ordgoodsId);
							criteriag.andStoreIdEqualTo(ordstorId);
							// 使用条件
							List<GoodsCoupon> listg = goodsCouponService.list(exampleg);
							if (listg.size() > 0) {
								// 有值说明可使用,使用成功后需要将红包券置失效
								usersCoupon.get(0).setIsUsed(DBConst.TRUE);
								double actualPay = sumAmount - amount;
								list.get(0).setActualPay(actualPay);
								list.get(0).setCouponId(couponId);
								String resultorder = ordersDetailService.edit(list.get(0));// 订单信息中实际支付金额写进满减后的金额
								if (SUCCESS.equals(resultorder)) {
									// 订单满减成功后将红包券置失效
									String result = usersCouponService.edit(usersCoupon.get(0));
									if (SUCCESS.equals(result)) {
										errorCode = SUCCESS_ERROR_CODE;
										errorMsg = SUCCESS_ERROR_MSG;
									}
								}
							} else {
								errorCode = COUPON_USE_ERROR_CODE;
								errorMsg = COUPON_USE_ERROR_MSG;
							}
						}

					} else {
						errorCode = ORDER_ERROR_CODE;
						errorMsg = ORDER_ERROR_MSG;
					}
				}
			} else {
				errorCode = LOGIN_ERROR_CODE;
				errorMsg = LOGIN_ERROR_MSG;
			}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "usecoupon", e.toString(), "使用满减券", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		return resultMap;
	}

	/**
	 * 使用红包券
	 * 
	 * @param request
	 * @param response
	 * @param token
	 * @param appId
	 * @return
	 */
	@RequestMapping(value = "/useredpac")
	@ResponseBody
	public Map<String, Object> useredpac(HttpServletRequest request, HttpServletResponse response, String token,
			String appId, String orderNo, String couponId) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			UsersMall usersMall = getUsersByTokenAndAppId(token, appId);
			if (usersMall != null) {
				if (StringHelper.isNotBlank(orderNo) && StringHelper.isNotBlank(couponId)) {
					Date date = new Date();
					String userId = usersMall.getId();
					OrdersDetailExample example = new OrdersDetailExample();
					com.itic.mall.system.orders.detail.persistence.model.OrdersDetailExample.Criteria criteria = example
							.createCriteria();
					criteria.andIsEffectiveEqualTo(DBConst.TRUE);
					criteria.andOrderNoEqualTo(orderNo);
					criteria.andUserIdEqualTo(userId);
					criteria.andStateEqualTo("1");//
					List<OrdersDetail> list = ordersDetailService.list(example);
					UsersCouponExample exampleuc = new UsersCouponExample();
					com.itic.mall.system.users.usercoupon.persistence.model.UsersCouponExample.Criteria criteriauc = exampleuc
							.createCriteria();
					criteriauc.andIsEffectiveEqualTo(DBConst.TRUE);
					criteriauc.andCouponIdEqualTo(couponId);
					criteriauc.andStartTimeLessThan(date);
					criteriauc.andEndTimeGreaterThan(date);
					criteriauc.andTypeEqualTo("002");// 红包券
					criteriauc.andIsUsedEqualTo(DBConst.FALSE);
					List<UsersCoupon> usersCoupon = usersCouponService.list(exampleuc);
					if (list.size() > 0 && usersCoupon.size() > 0) {
						// 商品信息
						// 商品信息
						OrdersItemExample exampleitem = new OrdersItemExample();
						com.itic.mall.system.orders.item.persistence.model.OrdersItemExample.Criteria criteriaitem = exampleitem
								.createCriteria();
						criteriaitem.andIsEffectiveEqualTo(DBConst.TRUE);
						criteriaitem.andOrderNoEqualTo(orderNo);
						List<OrdersItem> listgoods = ordersItemService.list(exampleitem);
						// 查看该订单是否适用于此红包券。先获取红包券ID和该订单所属的商家ID和商品ID
						String ordstorId = listgoods.get(0).getStoreId();
						String ordgoodsId = listgoods.get(0).getGoodsId();
						double sumAmount = list.get(0).getSumAmount();// 使用红包前的金额
						double amount = usersCoupon.get(0).getAmount();// 红包券金额
						// 1.获取红包券适用的商家和商品
						GoodsCouponExample exampleg = new GoodsCouponExample();
						com.itic.mall.system.goods.coupon.persistence.model.GoodsCouponExample.Criteria criteriag = exampleg
								.createCriteria();
						criteriag.andIsEffectiveEqualTo(DBConst.TRUE);
						criteriag.andCouponIdEqualTo(couponId);
						criteriag.andGoodsIdEqualTo(ordgoodsId);
						criteriag.andStoreIdEqualTo(ordstorId);
						// 是指定可使用商品
						List<GoodsCoupon> listg = goodsCouponService.list(exampleg);
						if (listg.size() > 0) {
							// 有值说明可使用,使用成功后需要将红包券置失效
							usersCoupon.get(0).setIsUsed(DBConst.TRUE);
							double actualPay = sumAmount - amount;
							list.get(0).setActualPay(actualPay);
							list.get(0).setCouponId(couponId);
							;// 优惠券ID
							String resultorder = ordersDetailService.edit(list.get(0));// 订单信息中实际支付金额写进满减后的金额
							if (SUCCESS.equals(resultorder)) {
								// 订单满减成功后将红包券置失效
								String result = usersCouponService.edit(usersCoupon.get(0));
								if (SUCCESS.equals(result)) {
									errorCode = SUCCESS_ERROR_CODE;
									errorMsg = SUCCESS_ERROR_MSG;
								} else {
									errorCode = COUPON_USE_ERROR_CODE;
									errorMsg = COUPON_USE_ERROR_MSG;
								}
							}
						} else {
							errorCode = COUPON_USE_ERROR_CODE;
							errorMsg = COUPON_USE_ERROR_MSG;
						}

					} else {
						errorCode = ORDER_ERROR_CODE;
						errorMsg = ORDER_ERROR_MSG;
					}
				}
			} else {
				errorCode = LOGIN_ERROR_CODE;
				errorMsg = LOGIN_ERROR_MSG;
			}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "useredpac", e.toString(), "使用红包券", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		return resultMap;
	}
	
	
	@RequestMapping(value = "/afterSaleExpress")
	@ResponseBody
	public Map<String, Object> addAfterSaleExpress(HttpServletResponse response,String appId,String token,String expressNo,String afterSafeId,String phone,String expressId){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			if(StringUtils.isNoneBlank(token,appId,expressId,expressNo,phone,afterSafeId)) {
				UsersMall usersMall = this.getUsersByTokenAndAppId(token, appId);
				if(usersMall !=null) {
					//获取用户未过期的优惠券
					OrdersAftersale aftersale =  this.ordersAftersaleService.get(afterSafeId);
					AfterSaleDealType afterSaleDealType = AfterSaleDealType.getType(aftersale.getDealState());
					switch (afterSaleDealType) { 
						case AgreeRefund:
							aftersale.setExpressNo(expressNo);
							aftersale.setUserPhone(phone);
							ProjectExpress projectExpress = this.projectExpressService.get(expressId);
							if(projectExpress!=null) {
								aftersale.setExpressCompanyName(projectExpress.getExpressCompany());;
								aftersale.setExpressCompanyNo(projectExpress.getId());
							}
							this.ordersAftersaleService.edit(aftersale);
							errorCode = SUCCESS_ERROR_CODE;
							errorMsg = SUCCESS_ERROR_MSG;
							break;
						case Refunding:
						case RefundClose:
						case RefundSuccess:
						case Pending:
						case Refuse:
						case CanceAlpply:
							errorCode = NOT_AGREE_RETURN_ERROR_CODE;
							errorMsg = NOT_AGREE_RETURN_ERROR_MSG;
							break;
					}
				}else{
					// 提示登录失效
					errorCode = PARAM_ERROR_CODE;
					errorMsg = PARAM_ERROR_MSG;
				}
			}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "canceAfterSale", e.toString(), "撤销售后申请", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}
	
	@RequestMapping(value="calActualMoney")
	@ResponseBody
	public Map<String, Object> calActualMoney(HttpServletResponse response,String token,String appId,String skuIdCounts,String couponId,String isUsePoint,Double expressFee){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			if(StringUtils.isNoneBlank(token,appId,skuIdCounts)) {
				UsersMall usersMall = this.getUsersByTokenAndAppId(token, appId);
				if(usersMall !=null) {
					Map<String, Double> dataMap = new HashMap<>();
					Map<String, String> skuMap = this.parseSkuIdCounts(skuIdCounts);
					double actualMoney = 0;
					double compareAmount=0;
					boolean isPoint = false;
					boolean isUseSYSCoupon = false;
					
					for(String key :skuMap.keySet()) {
						GoodsSpu goodsSpu = this.goodsSpuService.getBySku(key);
						GoodsSku goodsSku = this.goodsSkuService.get(key);
						if(goodsSku!=null) {
							int count = Integer.parseInt(skuMap.get(key));
							Map<String, Object> skuPriceMap = this.ordersItemService.calPrice(usersMall.getId(),goodsSpu.getIsGoodsCoupon(),key,count);
							actualMoney +=(Double)skuPriceMap.get(key);
							if(goodsSpu.getIsSysCoupon()!=null &&"1".equals(goodsSpu.getIsSysCoupon()))
								compareAmount +=(Double)skuPriceMap.get(key);
							
						}
						isPoint = "1".equals(goodsSpu.getIsJifenExchange())?true:false;
						isUseSYSCoupon = "1".equals(goodsSpu.getIsSysCoupon())?true:false;
					}
					if(isUseSYSCoupon && StringUtils.isNotEmpty(couponId))
						actualMoney = this.usersCouponService.calCouponPrice(couponId, actualMoney);
					if(isPoint) {
						//计算使用惠金币 算实际支付钱
						dataMap = this.projectScoreService.calUserScoreRatio(usersMall,compareAmount);
						Double deducMoney = dataMap.get("deduc")==null?0.00:dataMap.get("deduc");
						if(StringUtils.isNotEmpty(isUsePoint) && "1".equals(isUsePoint))
							actualMoney = actualMoney - deducMoney;
					}else{
						dataMap.put("use",0d);
						dataMap.put("deduc",0d);
					}
					if(expressFee !=null) 
						actualMoney +=expressFee;
					dataMap.put("actualPay",actualMoney);
					dataMap.put("compareAmount",compareAmount);
					resultMap.put(DATA, dataMap);
					errorCode = SUCCESS_ERROR_CODE;
					errorMsg = SUCCESS_ERROR_MSG; 
				}else{
					// 提示登录失效
					errorCode = LOGIN_ERROR_CODE;
					errorMsg = LOGIN_ERROR_MSG;
				}
			}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "calActualMoney", e.toString(), "计算实际支付", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}
	@RequestMapping(value="afterSale/list")
	@ResponseBody
	public Map<String, Object> afterSaleList(HttpServletResponse response,String appId,String token){
			Map<String, Object> resultMap = new HashMap<String, Object>();
			String errorCode = PARAM_ERROR_CODE;
			String errorMsg = PARAM_ERROR_MSG;
			try {
				if(StringUtils.isNoneBlank(token,appId)) {
					UsersMall usersMall = this.getUsersByTokenAndAppId(token, appId);
					if(usersMall !=null) {
						List<OrdersAftersale> ordersAftersales =this.ordersAftersaleService.getafterSaleListByUserId(usersMall.getId());
						List<Map<String, Object>> listMap = new ArrayList<>();
						for(OrdersAftersale aftersale :ordersAftersales) {
							Map<String, Object> detailMap = new HashMap<>();
							GoodsDetailVo goodsDetailVo = this.goodsSkuService.getSkuDetailBySkuId(aftersale.getGoodsId(),aftersale.getCount());
							detailMap.put("good", goodsDetailVo);
							detailMap.put("totalCount", aftersale.getCount());
							detailMap.put("totalAmount", aftersale.getRefunfAmount());
							detailMap.put("expressFee", aftersale.getExpressFee());
							detailMap.put("dealState", aftersale.getDealState());
							detailMap.put("afterSaleId", aftersale.getId());
							listMap.add(detailMap);
						}
						resultMap.put(DATA, listMap);
						errorCode = SUCCESS_ERROR_CODE;
						errorMsg = SUCCESS_ERROR_MSG; 
					}else{
						// 提示登录失效
						errorCode = LOGIN_ERROR_CODE;
						errorMsg = LOGIN_ERROR_MSG;
					}
				}
			} catch (Exception e) {
				errorCode = SERVER_ERROR_CODE;
				errorMsg = SERVER_ERROR_MSG;
				logException("OrdersdetailInterface", "afterSaleList", e.toString(), "售后列表", e);
			}
			resultMap.put(CODE, errorCode);
			resultMap.put(MSG, errorMsg);
			isCrrossDomain(response);
			return resultMap;
		}
	@RequestMapping(value="express/info")
	@ResponseBody
	public Map<String, Object> getExpressInfo(HttpServletResponse response, String token,String appId,String orderNo,String skuId){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try {
			if(StringUtils.isNoneBlank(orderNo,skuId)) {
				//UsersMall usersMall = this.getUsersByTokenAndAppId(token, appId);
				//if(usersMall !=null) {
					OrdersItem ordersItem = this.ordersItemService.getOrdersItemBySpuIdAndOrderNo(skuId, orderNo);
					Map<String, Object> goodMap = new HashMap<>();
					if(ordersItem!=null && StringUtils.isNotEmpty(ordersItem.getExpressId())) {
						ProjectExpress projectExpress = this.projectExpressService.get(ordersItem.getExpressId());
						GoodsSpu goodsSpu = goodsSpuService.getBySku(ordersItem.getSkuId());
						goodMap.put("mainImageUrl", goodsSpu.getMainImageUrl());
						goodMap.put("state", ordersItem.getState());
						goodMap.put("expressName", projectExpress.getExpressCompany());
						goodMap.put("expressPhone", projectExpress.getExpressPhone());
						goodMap.put("expressNo", ordersItem.getExpressNo());
						Object obj = this.orderExpressService.getWuliuMsgByCodeAndNum(projectExpress.getExpressCompanyNo(), ordersItem.getExpressNo());
						goodMap.put("expressList", obj);
					}
					resultMap.put(DATA, goodMap);
					errorCode = SUCCESS_ERROR_CODE;
					errorMsg = SUCCESS_ERROR_MSG; 
				/*}else{
					errorCode = LOGIN_ERROR_CODE;
					errorMsg = LOGIN_ERROR_MSG;
				}*/
			}
		} catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("OrdersdetailInterface", "getExpressInfo", e.toString(), "订单物流信息", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
	}
	@ResponseBody
	@RequestMapping(value="timer/cal/actual")
	public void timerActual() {
		
		this.ordersItemService.calActualOutOfDays();
		
	}
}